import { Repository } from 'typeorm';
import { AppDataSource } from '../../config/database';
import { PolicyNews, PolicyNewsType } from '../../entities/PolicyNews';

export class PolicyNewsService {
  private policyNewsRepository: Repository<PolicyNews>;

  constructor() {
    this.policyNewsRepository = AppDataSource.getRepository(PolicyNews);
  }

  /**
   * 获取政策新闻列表
   */
  async getPolicyNewsList(query: any = {}): Promise<{ news: PolicyNews[]; total: number }> {
    const { 
      page = 1, 
      pageSize = 10, 
      type, 
      isActive, 
      title, 
      startDate, 
      endDate,
      sortField = 'publishTime',
      sortOrder = 'DESC'
    } = query;
    
    const queryBuilder = this.policyNewsRepository.createQueryBuilder('news');
    
    // 添加类型过滤
    if (type !== undefined) {
      queryBuilder.andWhere('news.type = :type', { type });
    }
    
    // 添加状态过滤
    if (isActive !== undefined) {
      queryBuilder.andWhere('news.isActive = :isActive', { isActive });
    }
    
    // 添加标题搜索
    if (title) {
      queryBuilder.andWhere('news.title LIKE :title', { title: `%${title}%` });
    }
    
    // 添加日期范围搜索
    if (startDate) {
      queryBuilder.andWhere('news.publishTime >= :startDate', { startDate: new Date(startDate) });
    }
    
    if (endDate) {
      queryBuilder.andWhere('news.publishTime <= :endDate', { endDate: new Date(endDate) });
    }
    
    if(sortField){
      // 使用传入的排序参数，默认按发布时间倒序
      queryBuilder.orderBy(`news.${sortField}`, sortOrder as 'ASC' | 'DESC');
    }else{
      queryBuilder.orderBy(`news.publishTime`,  'DESC');
    }

    
    // 分页
    const total = await queryBuilder.getCount();
    const news = await queryBuilder
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getMany();

    return { news, total };
  }

  /**
   * 获取政策新闻详情
   */
  async getPolicyNewsById(id: string): Promise<PolicyNews | null> {
    return await this.policyNewsRepository.findOne({ where: { id } });
  }

  /**
   * 创建政策新闻
   */
  async createPolicyNews(newsData: Partial<PolicyNews>, userId: string): Promise<PolicyNews> {
    const news = this.policyNewsRepository.create({
      ...newsData,
      publishTime: newsData.publishTime || new Date(),
      createBy: userId,
      updateBy: userId
    });
    
    return await this.policyNewsRepository.save(news);
  }

  /**
   * 更新政策新闻
   */
  async updatePolicyNews(id: string, newsData: Partial<PolicyNews>, userId: string): Promise<PolicyNews | null> {
    const news = await this.getPolicyNewsById(id);
    
    if (!news) {
      return null;
    }
    
    Object.assign(news, {
      ...newsData,
      updateBy: userId
    });
    
    return await this.policyNewsRepository.save(news);
  }

  /**
   * 删除政策新闻
   */
  async deletePolicyNews(id: string): Promise<boolean> {
    try {
      const result = await this.policyNewsRepository.delete(id);
      return result.affected ? result.affected > 0 : false;
    } catch (error) {
      console.error('删除政策新闻失败:', error);
      return false;
    }
  }

  /**
   * 更新政策新闻状态
   */
  async updatePolicyNewsStatus(id: string, isActive: boolean, userId: string): Promise<boolean> {
    try {
      const result = await this.policyNewsRepository.update(
        { id },
        { 
          isActive,
          updateBy: userId,
          updateTime: new Date()
        }
      );
      return result.affected ? result.affected > 0 : false;
    } catch (error) {
      console.error('更新政策新闻状态失败:', error);
      return false;
    }
  }

  /**
   * 根据类型获取政策新闻列表（前台接口）
   */
  async getNewsByType(type: PolicyNewsType, limit: number = 10): Promise<PolicyNews[]> {
    return await this.policyNewsRepository.find({
      where: {
        type,
        isActive: true
      },
      order: {
        publishTime: 'DESC'
      },
      take: limit
    });
  }
}

export const policyNewsService = new PolicyNewsService(); 